#!/usr/bin/env python

"""
An echo client that allows the user to send multiple lines to the server.
Entering a blank line will exit the client.
"""

import getopt
import socket
import sys
import select
import time
import os

size = 1024

def establish_connection(optlist):
    myserver=optlist[1]
    myserverport=int(optlist[2])
    myname=optlist[3]
    
    #host = 'localhost'
    host=myserver
    port = myserverport
    
    print "[CONSOLE] ***Client now Started***\n"
    print "[CONSOLE] Connecting to server @%s, PORT: %d" %(host,port)
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host,port))
        print "[CONSOLE] Connected\n"
    except:
        print "[CONSOLE] ERROR in connection. Check Server IP and port no."    
        sys.exit()
        
    """Register with server"""
    print "[CONSOLE] Registering with the server"
    s.send('#'+myname)
    data = s.recv(size)
    if (data=='done'):
        print "[CONSOLE] Registered with the server\n"
    else:
        print "[CONSOLE]Registration failed. Check server IP address and port no."
        sys.exit()

    return s


def check_special_command(sp_str,mysock):    
    if('\exit' in sp_str):
        mysock.send('\exit')
        print "[CONSOLE] Exit Command detected. Closing connection"
        mysock.close()
        sys.exit()
    
def usage():
    print "USAGE:"
    sys.exit()

def clrscr():
	"""This function clears the screen according to the OS it is on."""
	if os.name == "posix":
		os.system('clear')
	else:
		os.system('CLS')

def mygetopt(myargv):
    
    if(len(myargv) > 2):
            opt,args = getopt.getopt(myargv[1:],"h:",['server=','port=','clientname='])	
            for option,value in opt:
                    if option == "-h":
                            usage()
                    elif option == "--server":
                            myserver=value
                    elif option in "--port":
                            myserverport=value
                    elif option in "--clientname":
                            myname=value
                    else:
                            print "Unhandled option"
                            usage()
    else:
            usage()

    return [1,myserver,myserverport,myname]

def main():
    clrscr()
    optlist=[]
    optlist=mygetopt(sys.argv)    
    
    s=establish_connection(optlist)
    
    print s.getsockname()
    
    myserver=optlist[1]
    myserverport=int(optlist[2])
    myname=optlist[3]
 
    inputx = [s,sys.stdin]
    
    
    while 1:    
        sys.stdout.write('%')   
        sys.stdout.flush()
        inputready,outputready,exceptready = select.select(inputx,[],[])

        for tmp in inputready:
            if tmp == s:
                # handle the server socket
                data = s.recv(size)
                if(data=='\\exit'):
                    print "Received Exit Command from the server"
                    s.send('\exit')
                    s.shutdown(socket.SHUT_RDWR)
                    s.close()
                    sys.exit()
                print "\n"
                print data
            elif tmp == sys.stdin:
                # handle standard input
                line = sys.stdin.readline()
                if line == '\n':
                    break
                
                if(line[0] == '\\') and (line[1] == '@'):
                    """PRIVATE CHAT"""
                    if(':' in line):
                        print "[CONSOLE] Private chat"
                        s.send(line)
                    else:
                        print "[CONSOLE] for private chat use as shown below"
                        print "EXAMPLE: @clientname:Hello, This is a provate chat"
                elif(line[0] == '\\'):
                    """SPECIAL COMMAND"""
                    check_special_command(line,s)
                    s.send(line)
                else:
                    """Group Chat"""
                    print "[CONSOLE] Group Chat"
                    s.send(line)
                
                


if __name__ == "__main__":
    main()
    